<?

class ss_cli_command_mangle extends ss_cli_command{
	protected $mangled;
	
	
	public function execute(){
		return call_user_func_array(array($this,'mangle'),func_get_args());
	}

	static public function setEnum($data){
		return array($data);
	}
	
	static public function stripNewline(&$row){
		foreach($row as $key=>$val){
			if(is_string($val)) {
				$row[$key]=trim(str_replace(array('\n',"\n","\r",'  '),array('','','',' '),$val));
				if($val!==$row[$key]) print($row[$key]."\n");
			}//$row[$key]=trim($val,"\n"));
		}
		//return $row;
	}
	
	static public function getFileBasename($img,$prefix=''){
		return ($prefix.basename($img));
	}
	
	static public function removeTimestamps(&$data){
		if(isset($data['created_at'])) unset($data['created_at']);
		if(isset($data['updated_at'])) unset($data['updated_at']);
		//return $data;
	}
	
	static public function properSlug($row){
		if($row['slug']){
			$slug=strtolower($row['slug']);
			$slug=mb_eregi_replace('(å|ä)','a',$slug);
			$slug=mb_eregi_replace('ö','o',$slug);
			$slug=mb_eregi_replace('(é|è)','a',$slug);
			$slug=mb_eregi_replace(' ','_',$slug);
			$slug=implode('_',preg_split('/[^a-zA-Z0-9-]+/',$slug));
			$row['slug']=mb_eregi_replace('__','_',$slug);
			//print($slug."\n");
		}
		return $row;
	}
	public function mangle($settings='stripnewline,removetimestamps',$source=null){
		$settings=explode(',',$settings);
		if(is_null($source)) $source=SITE_DOCTRINE_DATA_PATH.DIRECTORY_SEPARATOR.'dump'.DIRECTORY_SEPARATOR.'raw_dump.yml';
		$this->mangled=Spyc::YAMLLoad($source);
		foreach($this->mangled as $table=>$rows){
			if($pos=strpos($table,'Translation')){
				$tTable=substr($table,0,$pos);
				foreach($rows as $key=>$row){
					$id=explode('_',$key);
					unset($row['lang']);
					unset($row[$tTable]);
					if(in_array('stripnewline',$settings)) self::stripNewline($row);
					if(in_array('splitusertext',$settings)){
						if($tTable=='User') {
							$row=splitUserText($row,$id[2]);
						}
					}
					if(count($row)>0)$this->mangled[$tTable][$tTable.'_'.$id[1]]['Translation'][$id[2]]=$row;
				}
				unset($this->mangled[$table]);
			} else {
				foreach($rows as $key=>$row){
					//$row=self::removeTimestamps($row);
					if(in_array('removetimestamps',$settings)) self::removeTimestamps($row);
					if(in_array('stripnewline',$settings)) self::stripNewline($row);
					//$row=properSlug($row);
					//if($table=='User') $row['img']=getFileBasename($row['img']);
					//if($table=='Structure') $row['header_method']=setEnum($row['header_method']);
				}
			}
			$this->mangled[$table][$key]=$row;
		}
		if($this->save()) return true;//$this->mangled;
		return false;
	}
	
	public function save(){
		return file_put_contents(SITE_DOCTRINE_DATA_PATH.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'mangled.yml',Spyc::YAMLDump($this->mangled));
	}
}

?>